package com.cms.manager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.cms.model.ChannelPercent;
import com.cms.service.ChannelPercentService;
import com.cms.service.ChannelPercentServiceImpl;
import com.util.Singleton;

public class ChannelPercentManager extends Singleton {
	
	private ChannelPercentService service = null;
	private Map<Integer, ChannelPercent> map = null;
	private Map<Integer, List<ChannelPercent>> chpmap = null;
	private List<ChannelPercent> list = null;
	
	
	public static ChannelPercentManager getInstance()
	{
		return (ChannelPercentManager) ChannelPercentManager.getInstance(ChannelPercentManager.class.getName());
	}
	public ChannelPercentManager()
	{
		map = new HashMap<Integer, ChannelPercent>();
		list = new ArrayList<ChannelPercent>();
		service = new ChannelPercentServiceImpl();
		for (ChannelPercent p : service.getChannelPercent())
		{
			map.put(p.getId(), p);
			list.add(p);
			
		}
	}
	
	public ChannelPercent getChannelPercent(int id)
	{
		return map.get(id);
	}
	
	public List<ChannelPercent> getChannelPercents()
	{
		return list;
	}
	
	public Map<Integer,List<ChannelPercent>> getChpMap()
	{
		chpmap = new HashMap<Integer, List<ChannelPercent>>();
		for (ChannelPercent p : list) {
			if(!chpmap.containsKey(p.getChannelid())){
				chpmap.put(p.getChannelid(), new ArrayList<ChannelPercent>());
			}
			chpmap.get(p.getChannelid()).add(p);
		}
		
		return chpmap;
	}
	public Map<String,ChannelPercent> getChpByChannelAndAversion(){
		Map<String,ChannelPercent> m = new HashMap<String,ChannelPercent>();
		for (ChannelPercent item : list) {
			m.put(item.getChannelid()+"_"+item.getAppversionnumber(), item);
		}
		return m;
	}
	
	public boolean saveChannelPercent(String type, ChannelPercent model)
	{
			if (type.equals("insert"))
			{
				if(service.saveChannelPercent(model))
				{
					if(!map.containsKey(model.getId())&&model.getId()>0){
						map.put(model.getId(), model);
						list.add(map.get(model.getId()));
					}
					return true;
				}
			}
			else if (type.equals("delete"))
			{
				if(service.deleteChannelPercent(model))
				{
					map.remove(model.getId());
					for (int n = 0; n < list.size(); n++)
					{
						if (list.get(n).getId() == model.getId())
						{
							list.remove(n);
							break;
						}
					}
					return true;
				}
			}
			else 
			{
				if(service.updateChannelPercent(model))
				{
					model = service.getChannelPercent(model);
					map.put(model.getId(), model);
					for (int n = 0; n < list.size(); n++)
					{
						if (list.get(n).getId() == model.getId())
						{
							list.set(n, model);
							break;
						}
					}
					return true;
				}
			}
			return false;
	}
	
}
